package avicit.bdp.dms.oauth2.handler;

import avicit.bdp.dms.oauth2.WebUtils;
import avicit.bdp.dms.oauth2.token.AccessToken;
import avicit.bdp.dms.oauth2.validator.AbstractClientDetailsValidator;
import avicit.bdp.dms.oauth2.validator.ClientCredentialsClientDetailsValidator;
import org.apache.commons.lang3.StringUtils;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO
 *
 * @author xugb
 * @date 2024/4/12 14:44
 */

public class ClientCredentialsTokenHandler extends AbstractOAuthTokenHandler {
    private static final Logger LOG = LoggerFactory.getLogger(ClientCredentialsTokenHandler.class);

    public ClientCredentialsTokenHandler() {
    }

    public boolean support(OAuthTokenRequest tokenRequest) throws OAuthProblemException {
        String grantType = tokenRequest.getGrantType();
        String username = tokenRequest.getUsername();
        return GrantType.CLIENT_CREDENTIALS.toString().equalsIgnoreCase(grantType) && StringUtils.isEmpty(username);
    }

    @Override
    public void handleAfterValidation() throws OAuthProblemException, OAuthSystemException {
        AccessToken accessToken = this.oauthTokenService.createClientCredentialsToken(this.tokenRequest.getClientId(), this.tokenRequest.getScopes());
        OAuthResponse tokenResponse = this.createTokenResponse(accessToken);
        LOG.debug("'client_credentials' response: {}", tokenResponse);
        WebUtils.writeOAuthJsonResponse(this.response, tokenResponse);
    }

    @Override
    protected AbstractClientDetailsValidator getValidator() {
        return new ClientCredentialsClientDetailsValidator(this.tokenRequest);
    }
}
